package com.engine.jucailinkq.attendance.workflow.action;

import com.engine.jucailinkq.attendance.workflow.service.MakeUpClockInService;
import com.engine.jucailinkq.attendance.workflow.service.impl.MakeUpClockInServiceImpl;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.common.util.ServiceUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 补打卡提交校验action
 */
@Slf4j
public class MakeUpClockInAction implements Action {

    private MakeUpClockInService makeUpClockInService = ServiceUtil.getService(MakeUpClockInServiceImpl.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        BaseBean bs = new BaseBean();
        // 流程表单主表数据
        HashMap<String,String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
        // 流程表单明细表数据
        List<Map<String, String>> detailTableData = CommonUtil.getDetailTableInfo(requestInfo,0);
        //补打卡人员
        String userId = mainTableData.get("bdkry");
        Map<String,List<Map<String, String>>> detailGroupMap = detailTableData.stream().collect(Collectors.groupingBy(e->Util.null2String(e.get("bdkr"))));

        for (Map.Entry<String,List<Map<String, String>>> tableEntry :detailGroupMap.entrySet()){
            List<Map<String, String>> detailGroupByUserList = tableEntry.getValue();
            Map<String, Object> params = Maps.newHashMap();
            if ("".equals(tableEntry.getKey())){
                params.put("userId",userId);
            }else {
                params.put("userId",tableEntry.getKey());
            }
            params.put("submitDate",DateUtil.getCurrentDate());
            params.put("submitStr","bdkrq");
            params.put("submitDataList",detailGroupByUserList);
            /**
             * 考勤周期校验
             */
            if (detailGroupByUserList == null || detailGroupByUserList.size() == 0){
                log.error("明细表没有数据！");
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent("明细表没有数据！");
                return Action.FAILURE_AND_CONTINUE;
            }
            Map<String,Object> dataMap = makeUpClockInService.getKqCycleTimeIntervalCmd(params);
            List<Map<String,Object>> closeList = (List<Map<String,Object>>)dataMap.get("closeList");
            List<String> nocycleList = (List<String>)dataMap.get("nocycleList");
            List<Map<String,Object>> dateList = (List<Map<String,Object>>)dataMap.get("dataList");

            boolean status = (boolean)dataMap.get("status");
            if (!status){
                log.error("该人员没有考勤周期");
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent("该人员没有考勤周期！");
                return Action.FAILURE_AND_CONTINUE;
            }
            if (closeList.size() > 0 || nocycleList.size() > 0){
                String message = "";
                if (nocycleList.size() > 0){
                    message = message +String.join(",",nocycleList)+"未找对对应的考勤周期；";
                }
                if (closeList.size() > 0){
                    List<String> list = closeList.stream().map(e->e.get("rq").toString()).collect(Collectors.toList());
                    message = message +String.join(",",list)+"对应的考勤周期的考勤周期已关账";
                }
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent(message);
                return Action.FAILURE_AND_CONTINUE;
            }

            /**
             * 补打卡项目校验
             */
            try {
                Map<String,List<Map<String, String>>> dataGroupByBdlxs = Maps.newHashMap();

                //按照考勤周期对补打卡数据进行分类
                for (int i=0;i<dateList.size();i++){
                    String startDate = Util.null2String(dateList.get(i).get("startDate"));
                    String endDate = Util.null2String(dateList.get(i).get("endDate"));
                    List<Map<String, String>> datas = Lists.newArrayList();
                    for (Map<String, String> detailTable:detailGroupByUserList){
                        String bdkrq = detailTable.get("bdkrq");
                        if (DateUtil.getTime(startDate).compareTo(DateUtil.getTime(bdkrq)) <=0 &&
                                DateUtil.getTime(endDate).compareTo(DateUtil.getTime(bdkrq)) >=0){
                            datas.add(detailTable);
                        }
                    }
                    if (datas.size() > 0){
                        dataGroupByBdlxs.put(startDate+","+endDate,datas);
                    }
                }
                /**
                 *
                 */
                for (Map.Entry<String,List<Map<String, String>>> detailentry :dataGroupByBdlxs.entrySet()){
                    List<Map<String, String>> details = detailentry.getValue();
                    String startDate = detailentry.getKey().split(",")[0];
                    String endDate = detailentry.getKey().split(",")[1];

                    Map<String,List<Map<String, String>>> dataGroupByBdlx =   details.stream().collect(Collectors.groupingBy(e->e.get("bdklx")));

                    String bdklxs="";
                    for (Map.Entry<String,List<Map<String, String>>> entry :dataGroupByBdlx.entrySet()){
                        String bdklx = entry.getKey();
                        bdklxs = bdklxs + bdklx +",";
                    }
                    bdklxs = bdklxs.substring(0,bdklxs.length()-1);
                    String sql = "select id,kqzqnxzsycs,ygbcycb,xzsydcs,hbjrdkqxm from uf_jcl_kq_kqxm where id in ("+bdklxs+")";
                    List<Map<String,Object>> items = DbTools.getSqlToList(sql);

                    Map<String,List<Map<String, Object>>> itemsGroupById =  items.stream().collect(Collectors.groupingBy(e->Util.null2String(e.get("id"))));


                    for (Map.Entry<String,List<Map<String, String>>> entry :dataGroupByBdlx.entrySet()){
                        String bdklx = entry.getKey();
                        //明细数据
                        List<Map<String, String>> detailDatas = entry.getValue();
                        //考勤项目
                        List<Map<String, Object>> item = itemsGroupById.get(bdklx);
                        int maxclockTimes = Integer.valueOf(item.get(0).get("xzsydcs").toString());
                        int clockTimes = detailDatas.size();

                        //计入限制次数的其他项目
                        String hbjrdkqxm = Util.null2String(item.get(0).get("hbjrdkqxm"));
                        //计入限制次数的其他项目的明细数据
                        List<Map<String, String>> list = dataGroupByBdlx.get(hbjrdkqxm);
                        if (list != null && list.size() > 0){
                            clockTimes += list.size();
                        }
                        sql = "select bdkry,dkrq from uf_jcl_kq_bdkjl where bdkry=? and bdklx=?";
                        List<Map<String,Object>> existsList =  DbTools.getSqlToList(sql,userId,bdklx);
                        log.debug("existsList : [{}]",existsList);
                        existsList = existsList.stream().filter(e->DateUtil.getTime(startDate).compareTo(DateUtil.getTime(e.get("dkrq").toString())) <=0 &&
                                DateUtil.getTime(endDate).compareTo(DateUtil.getTime(e.get("dkrq").toString())) >=0).collect(Collectors.toList());
                        clockTimes +=existsList.size();
                        log.debug("clockTimes : [{}],maxclockTimes : [{}]",clockTimes,maxclockTimes);
                        if (clockTimes > maxclockTimes){
                            //已达到请假上限
                            log.error("考勤项目已达到补打卡上限");
                            requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                            requestInfo.getRequestManager().setMessagecontent("考勤项目已达到补打卡上限！");
                            return Action.FAILURE_AND_CONTINUE;
                        }

                    }

                }
            }catch (Exception e){
                log.error("exception : [{}]",e);
            }
        }


        return Action.SUCCESS;
    }



}
